import cv2
import numpy as np
import matplotlib.pyplot as plt

# 图像二值化处理
def imgThreshold(img):
    rosource, binary = cv2.threshold(img, 127, 255, cv2.THRESH_BINARY)
    return binary

# 1.先水平分割，再垂直分割
# 对图片进行垂直分割
def verticalCut(img):
    (x, y) = img.shape  # 返回的分别是矩阵的行数和列数，x是行数，y是列数
    pointCount = np.zeros(y, dtype=np.float32)  # 每列黑色的个数
    x_axes = np.arange(0, y)
    # i是列数，j是行数
    tempimg = img.copy()
    for i in range(0, y):
        for j in range(0, x):
            # if j<15:
            if (tempimg[j, i] == 0):
                pointCount[i] = pointCount[i] + 1
    plt.plot(x_axes, pointCount)
    plt.show()
    start = []
    end = []
    # 对照片进行分割
    # print(pointCount)
    for index in range(1, y - 1):
        # 上个为0当前不为0，即为开始
        if ((pointCount[index - 1] == 0) & (pointCount[index] != 0)):
            start.append(index)
        # 上个不为0当前为0，即为结束
        elif ((pointCount[index] != 0) & (pointCount[index + 1] == 0)):
            end.append(index)
    imgArr = []
    # print(len(end),len(start))
    for i in range(len(end)):
        tempimg = img[:, start[i]:end[i]]
        imgArr.append(tempimg)
    return imgArr

# 对图片进行水平分割,返回照片数组
def horizontalCut(img):
    (x, y) = img.shape  # 返回的分别是矩阵的行数和列数，x是行数，y是列数
    pointCount = np.zeros(y, dtype=np.uint8)  # 每行黑色的个数
    x_axes = np.arange(0, y)
    for i in range(0, x):
        for j in range(0, y):
            if (img[i, j] == 0):
                pointCount[i] = pointCount[i] + 1
    plt.plot(x_axes, pointCount)
    plt.show()
    start = []
    end = []
    # 对照片进行分割
    # print(pointCount)
    for index in range(1, y):
        # 上个为0当前不为0，即为开始
        if ((pointCount[index] != 0) & (pointCount[index - 1] == 0)):
            start.append(index)
        # 上个不为0当前为0，即为结束
        elif ((pointCount[index] == 0) & (pointCount[index - 1] != 0)):
            end.append(index)
    newimg = {}
    for i in range(len(start)):
        newimg[i] = img[start[i]:end[i], :]
    cv2.waitKey()
    # plt.show()
    return newimg

# 输入的分别是原图,模板和标签
def matchTemplate(src, matchSrc):
    res = 0
    src = cv2.resize(src,(21,28))
    thre, src = cv2.threshold(src, 127, 255, cv2.THRESH_BINARY_INV)
    m = 21* 28 - np.sum(src)/255
    match = src - matchSrc
    n = 0
    for i in range(21):
        for j in range(28):
            if match[j, i] == 0:
                n = n + 1

    res = n-m
    return res
    # threshold = 0.4
    # loc = np.where(res >= threshold)  # 匹配程度大于%80的坐标y,x
    # loc = np.array(loc)
    # # print(loc.shape[1])
    # # if loc.shape[1] != 0:
    # #     return 1
    # # else:
    # #     return 0

def readmatch():
    temp = {}
    for i in range(13):
        # print(i)
        temp[i] = cv2.imread('pic/temple/'+str(i+1)+'.bmp')
        temp[i] = cv2.cvtColor(temp[i], cv2.COLOR_RGB2GRAY)
        temp[i] = imgThreshold(temp[i])
    return temp


dict = {'0':'A','1':'B','2':'C','3':'D','4':'E','5':'F','6':'G','7':'H','8':'I','9':'J','10':'K','11':'L','12':'M'}
# 先读取图片
img = cv2.imread("pic/word.png")
img = cv2.cvtColor(img,cv2.COLOR_RGB2GRAY)
img = imgThreshold(img)
match = []
match = readmatch()

result = horizontalCut(img)
for i in range(len(result)):
    result1 = verticalCut(result[i])
    # 再读取分割好的图片
    for j in range(len(result1)):
        best = 0
        now = matchTemplate(result1[j], match[0])
        for index in range(12):
            then = matchTemplate(result1[j], match[index+1])
            # print(now[0][0])
            if (then > 0 ):
                if (now < then):
                    now = then
                    best = index + 1
            
        print(best)
        print("找到了！该字符是"+str(dict[str(best)]))
        cv2.imshow('Find', result1[j])
        cv2.waitKey(0)
        cv2.destroyAllWindows()



